package com.caosy.grassthinkremote.util;

import cn.hutool.crypto.digest.MD5;
import com.caosy.grassthinkremote.common.BaseContext;
import com.caosy.grassthinkremote.common.GtrConstant;
import com.caosy.grassthinkremote.entity.User;
import com.caosy.grassthinkremote.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

@Component
public class BaseUtil {
    @Resource
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取当前用户的id
     * @return
     */
    public Long getCurUserId(HttpServletRequest request) {
        //查询用户id
        String username = (String) BaseContext.get(GtrConstant.LOCAL_USERNAME_KEY);
        //未查到，重新去redis查，然后再设到本地
        if (Objects.isNull(username)) {
            username = (String) redisTemplate.opsForValue().get(GtrConstant.REDIS_TOKEN_KEY_PREFIX
                    + MD5.create().digestHex16(request.getHeader("Authorization")));
            //重设到BaseContext中
            BaseContext.set(GtrConstant.LOCAL_USERNAME_KEY,username);
        }
        System.out.println(username);
        List<User> users = userMapper.getUserByNameAndPw(username, null);
        return users.get(0).getId();
    }
}
